package com.example.managemyself.viewmodel;

import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import com.example.managemyself.data.model.HealthData;
import com.example.managemyself.data.repository.HealthRepository;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class HealthViewModel extends AndroidViewModel {

    private HealthRepository repository;
    private LiveData<List<HealthData>> allHealthData;
    private MutableLiveData<Date> selectedDate = new MutableLiveData<>();
    private LiveData<HealthData> healthDataForSelectedDate;

    public HealthViewModel(Application application) {
        super(application);
        repository = new HealthRepository(application);
        allHealthData = repository.getAllHealthData();

        // Set initial date to today
        selectedDate.setValue(getStartOfDay(new Date()));

        healthDataForSelectedDate = Transformations.switchMap(selectedDate, date ->
                repository.getHealthDataByDate(date)
        );
    }

    public LiveData<List<HealthData>> getAllHealthData() {
        return allHealthData;
    }

    public LiveData<HealthData> getHealthDataForSelectedDate() {
        return healthDataForSelectedDate;
    }

    public void setSelectedDate(Date date) {
        selectedDate.setValue(getStartOfDay(date));
    }

    public void saveHealthData(float weight, float height, float sleepHours, String mood, int energyLevel) {
        Date date = selectedDate.getValue();
        if (date != null) {
            HealthData healthData = new HealthData(date, weight, height, sleepHours, mood, energyLevel);
            repository.insertOrUpdate(healthData);
        }
    }

    public String calculateBmi(float weight, float height) {
        if (height <= 0 || weight <= 0) {
            return "N/A";
        }
        float heightInMeters = height / 100;
        float bmi = weight / (heightInMeters * heightInMeters);
        return String.format("%.1f", bmi);
    }

    private Date getStartOfDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
} 